﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Base.Schema
{
    public enum Guid64Format
    {
        Hex,
        HexWithBraces,
        Uid
    }

    public class Guid64
    {
        private static Random _random;
        static Guid64()
        {
            Guid64._random = new Random();
        }

        public Guid64(ulong value)
        {
            Value = value;
        }

        public Guid64(string hexValue)
        {
            Value = ulong.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
        }

        public ulong Value { get; private set; }

        public override string ToString()
        {
            return this.ToString(Guid64Format.Hex);
        }

        public string ToString(Guid64Format format)
        {
            switch (format)
            {
                case Guid64Format.Hex:
                    return Value.ToString("x16");
                case Guid64Format.HexWithBraces:
                    return String.Format("{{{0}}}", Value.ToString("x16"));
                case Guid64Format.Uid:
                    return String.Format("uid-{0}", Value.ToString("x16"));
            }

            return this.ToString();
        }
        
        public static Guid64 Generate()
        {
            ulong value = 0;
            for (int i = 0; i < 8; ++i)
            {
                value <<= 8;
                value += (uint)_random.Next(0, 256);
            }

            return new Guid64(value);
        }

        public override bool Equals(object obj)
        {
            if (!(obj is Guid64))
            {
                return false;
            }

            return ((Guid64)obj).Value == this.Value;
        }

        public override int GetHashCode()
        {
            return (int)Value;
        }
    }
}
